<!DOCTYPE html>
<html>
<head>
    <title>Grapheditor</title>
    <!--[if IE]>
    <meta http-equiv="X-UA-Compatible" content="IE=5,IE=9">
    <![endif]-->
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" type="text/css" href="styles/grapheditor.css">
    <script type="text/javascript">
        var urlParams = (function (url) {
            var result = {};
            var idx = url.lastIndexOf('?');
            if (idx > 0) {
                var params = url.substring(idx + 1).split('&');
                for (var i = 0; i < params.length; i++) {
                    idx = params[i].indexOf('=');
                    if (idx > 0) {
                        result[params[i].substring(0, idx)] = params[i].substring(idx + 1);
                    }
                }
            }
            return result;
        })(window.location.href);
        mxLoadResources = false;
        window.mxBasePath = "./src";
    </script>
    <script type="text/javascript" src="js/Init.js"></script>
    <script type="text/javascript" src="deflate/pako.min.js"></script>
    <script type="text/javascript" src="deflate/base64.js"></script>
    <script type="text/javascript" src="jscolor/jscolor.js"></script>
    <script type="text/javascript" src="sanitizer/sanitizer.min.js"></script>
    <script type="text/javascript" src="js/mxClient.js"></script>
    <script type="text/javascript" src="js/EditorUi.js"></script>
    <script type="text/javascript" src="js/Editor.js"></script>
    <script type="text/javascript" src="js/Sidebar.js"></script>
    <script type="text/javascript" src="js/Graph.js"></script>
    <script type="text/javascript" src="js/Format.js"></script>
    <script type="text/javascript" src="js/Shapes.js"></script>
    <script type="text/javascript" src="js/Actions.js"></script>
    <script type="text/javascript" src="js/Menus.js"></script>
    <script type="text/javascript" src="js/Toolbar.js"></script>
    <script type="text/javascript" src="js/Dialogs.js"></script>
</head>
<body class="geEditor">
<script type="text/javascript" src="js/Dark.js"></script>
<script type="text/javascript">
    (function () {
        var editorUiInit = EditorUi.prototype.init;

        EditorUi.prototype.init = function () {
            editorUiInit.apply(this, arguments);
            this.actions.get('new').setEnabled(false);
            this.actions.get('export').setEnabled(false);
            this.actions.get('open').setEnabled(false);
            this.actions.get('import').setEnabled(false);
            this.actions.get('save').setEnabled(true);
            this.actions.get('saveAs').setEnabled(false);
            this.actions.get('export').setEnabled(false);
        };

        EditorUi.prototype.saveFile = function () {
            window.parent.postMessage({
                act: 'save',
                params: {

                }
            }, '*');
        };

        EditorUi.prototype.menubarHeight = 0;
        EditorUi.prototype.footerHeight = 0;

        mxResources.loadDefaultBundle = false;
        var bundle = mxResources.getDefaultBundle(RESOURCE_BASE, mxLanguage) || mxResources.getSpecialBundle(RESOURCE_BASE, mxLanguage);

        mxUtils.getAll([bundle, STYLE_PATH + '/default.xml'], function (xhr) {
            mxResources.parse(xhr[0].getText());

            var themes = {};
            themes[Graph.prototype.defaultThemeName] = xhr[1].getDocumentElement();

            var editorUi = new EditorUi(new Editor(urlParams['chrome'] == '0', themes));
            var graph = editorUi.editor.graph;

            var getPos = function () {
                var svg = null;
                var childNodes = graph.container.childNodes;
                for (var i = 0; i < childNodes.length; i++) {
                    if (childNodes[i].nodeName.toLocaleLowerCase() == 'svg') {
                        svg = childNodes[i];
                        break;
                    }
                }
                var data = {
                    p1: {left: 0, top: 0},
                    p2: {left: 0, top: 0},
                };
                if (svg != null) {
                    data = {
                        p1: {
                            left: svg.clientWidth / 2,
                            top: svg.clientHeight / 2,
                        },
                        p2: {
                            left: graph.container.clientWidth / 2 + graph.container.scrollLeft,
                            top: graph.container.clientHeight / 2 + graph.container.scrollTop,
                        }
                    };
                }
                return {
                    left: data.p2.left - data.p1.left,
                    top: data.p2.top - data.p1.top,
                };
            }

            var setPos = function (diff) {
                var svg = null;
                var childNodes = graph.container.childNodes;
                for (var i = 0; i < childNodes.length; i++) {
                    if (childNodes[i].nodeName.toLocaleLowerCase() == 'svg') {
                        svg = childNodes[i];
                        break;
                    }
                }
                if (svg == null) {
                    return;
                }
                graph.container.scrollLeft = svg.clientWidth / 2 + diff.left - graph.container.clientWidth / 2;
                graph.container.scrollTop = svg.clientHeight / 2 + diff.top - graph.container.clientHeight / 2;
            }

            var newXml;
            var newPos;
            var randXml;
            var backupParams;

            var changePost = function (immediately) {
                var randTmp = (randXml = Math.random());
                setTimeout(() => {
                    if (randTmp != randXml) {
                        return;
                    }
                    if (!backupParams) {
                        return;
                    }
                    newPos = getPos();
                    newXml = mxUtils.getPrettyXml(editorUi.editor.getGraphXml());
                    if (backupParams.xml && backupParams.xml.replace(/^<mxGraphModel(.*?)>/, '') == newXml.replace(/^<mxGraphModel(.*?)>/, '')) {
                        if (backupParams.scale && backupParams.scale == graph.getView().scale) {
                            if (typeof backupParams.diffpos === "object" && Math.abs(backupParams.diffpos.left - newPos.left) < 10 && Math.abs(backupParams.diffpos.top - newPos.top) < 10) {
                                return;
                            }
                        }
                    }
                    backupParams.xml = newXml;
                    window.parent.postMessage({
                        act: 'change',
                        params: {
                            xml: newXml,
                            scale: graph.getView().scale,
                            diffpos: newPos,
                        }
                    }, '*');
                }, immediately === true ? 0 : 200)
            }

            graph.getModel().addListener(mxEvent.CHANGE, mxUtils.bind(editorUi, function() { changePost(true) }));
            graph.getView().addListener(mxEvent.SCALE, mxUtils.bind(editorUi, function() {changePost(true) }));
            graph.container.addEventListener("scroll", changePost);

            window.addEventListener("message", function(event){
                var data = event.data;
                switch (data.act) {
                    case 'setXml':
                        try {
                            backupParams = data.params;
                            editorUi.editor.setGraphXml(mxUtils.parseXml(data.params.xml).documentElement);
                            typeof data.params.scale === "number" && graph.zoomTo(data.params.scale);
                            typeof data.params.diffpos === "object" && setPos(data.params.diffpos);
                        } catch (e) {

                        }
                        break;

                    case 'exportPNG':
                        try {
                            (function (name, scale, type) {
                                name = name || '未命名';
                                type = type || 'png';
                                scale = scale || 1;
                                var graph = editorUi.editor.graph;
                                var bounds = graph.getGraphBounds();
                                var width = Math.ceil(bounds.width / graph.view.scale * scale);
                                var height = Math.ceil(bounds.height / graph.view.scale * scale);
                                var source = '<?xml version="1.0" standalone="no"?>\r\n' + mxUtils.getXml(graph.getSvg(null, scale, 0))
                                var image = new Image()
                                image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(source)
                                var canvas = document.createElement('canvas')
                                canvas.width = width
                                canvas.height = height
                                var context = canvas.getContext('2d')
                                context.fillStyle = '#fff'
                                context.fillRect(0, 0, 10000, 10000)
                                image.onload = function () {
                                    context.drawImage(image, 0, 0)
                                    if (type == 'imageContent') {
                                        window.parent.postMessage({
                                            act: 'imageContent',
                                            params: {
                                                name: name,
                                                width: width,
                                                height: height,
                                                content: canvas.toDataURL(`image/${type}`)
                                            }
                                        }, '*');
                                    } else {
                                        var a = document.createElement('a')
                                        a.download = `${name}.${type}`
                                        a.href = canvas.toDataURL(`image/${type}`)
                                        a.click()
                                    }
                                }
                            })(data.params.name, data.params.scale, data.params.type);
                        } catch (e) {

                        }
                        break;
                }
            });

            window.parent.postMessage({
                act: 'ready',
                params: {}
            }, '*');

        }, function () {
            document.body.innerHTML = '<center style="margin-top:10%;">Error loading resource files. Please check browser console.</center>';
        });
    })();
</script>
</body>
</html>
